package openjdk.security;

import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by boot on 8/29/15.
 */
public class ECDSA {

    private String str = "asdfasdf";

    public static void main(String[] args) {
        ECDSA ec = new ECDSA();
        ec.jdkECDSA();
    }

    public void jdkECDSA() {
        // init private key
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
            keyPairGenerator.initialize(256);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
            ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();


            // 2. sign with private key

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            PrivateKey signPrivateKey = keyFactory.generatePrivate(keySpec);
            Signature signature = Signature.getInstance("SHA1withECDSA");
            signature.initSign(signPrivateKey);
            signature.update(str.getBytes());
            byte[] result = signature.sign();

            System.out.println(result);

            // verify
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
            KeyFactory kf = KeyFactory.getInstance("EC");
            PublicKey pubKey = kf.generatePublic(x509EncodedKeySpec);
            Signature sign = Signature.getInstance("SHA1withECDSA");
            sign.initVerify(pubKey);
            sign.update(str.getBytes());
            boolean b = sign.verify(result);
            System.out.println("jdk ec verify:" + b);


        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }

    }
}
